package btcdemo.btcdemo.model;

import btcdemo.btcdemo.security.RsaUtils;
import btcdemo.btcdemo.security.Sha256Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 钱包实体类
 * 
 * @author blues
 *
 */
public class Wallet {

	/* 存储所有用户的钱包 */
	public static final Map<String,Wallet> walletMap = new HashMap<>();


	/**
	 * 公钥（用户名）
	 */
	private String publicKey;
	/**
	 * 私钥（密码）
	 */
	private String privateKey;

	public String getPublicKey() {
		return publicKey;
	}

	public void setPublicKey(String publicKey) {
		this.publicKey = publicKey;
	}

	public String getPrivateKey() {
		return privateKey;
	}

	public void setPrivateKey(String privateKey) {
		this.privateKey = privateKey;
	}







	/**
	 * 正常定义一个钱包===================================================================================
	 */
	private Wallet(String publicKey, String privateKey) {
		this.publicKey = publicKey;
		this.privateKey = privateKey;
	}


	/* 生成一个钱包 */
	public static Wallet generateWallet() {
		Map<String, Object> initKey;
		try {
			// 本地生成公私钥对
			initKey = RsaUtils.initKey();
			String publicKey = RsaUtils.getPublicKey(initKey);
			String privateKey = RsaUtils.getPrivateKey(initKey);
			return new Wallet(publicKey, privateKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}







	/**
	 * 只包含公钥的钱包，用来给其他节点使用，其他节点在转账时需要用到=====================================================
	 */
	public Wallet(String publicKey) {
		this.publicKey = publicKey;
	}







	/**
	 * 获取钱包地址(sha256哈希为固定长度)==============================================================================
	 */
	public String getAddress() {
		return getAddressByPublicKey(publicKey);
	}


	public static String getAddressByPublicKey(String publicKey){
		if (publicKey!=null){
			return Sha256Utils.sha256(publicKey);
		}
		return null;
	}



}
